<?php

/**
 * template_content actions.
 *
 * @package    master_directory
 * @subpackage template_content
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class template_contentActions extends sfActions
{
	public function executeIndex(sfWebRequest $request)
	{
		$this->content_types = Doctrine_Core::getTable('ContentType')->retreiveActiveContentTypes();

		$template_id = $request->getParameter('template_id');

		$this->template = Doctrine_Core::getTable('Template')->find(array($template_id));

		$deletable = false;

		$template_content_arr = array();


		foreach ($this->content_types as $content_type){
			$templateContent = Doctrine_Core::getTable('TemplateContent')->getTemplateContent($template_id,$content_type->getId() );

			$template_content_arr[$content_type->getId()] = $templateContent;
			//echo 'content_type: ' . $content_type->getId(); exit();

			if($templateContent != null){
				$deletable = true;
			}
		}

		$this->deletable = $deletable;

		$this->template_content_arr = $template_content_arr;

		$this->all_levels = $this->getLevels($template_id);

		$this->footer_templates = $this->getTemplatesForFooter($this->template);

		$this->listings = $this->getListingsForTemplate($this->template);
		
	//	echo count($this->listings ); exit();

	}


	protected function getListingsForTemplate($template){
			
		$listingsForTemplate = array();
			
		$template2levels = $template->getTemplate2Level() ;
			
		$template_level_ids = array();
		foreach ($template2levels as $t2l) {
			array_push($template_level_ids, $t2l->getLevelId());
		}
			
		$directoryId = count($template2levels) > 0 ? $template2levels[0]->getLevel()->getCategory()->getMasterDirectoryId() : $template->getDirectoryForHomeTemplate()->getId();
			
		$directory_listings = Doctrine_Core::getTable('Listing')->retreiveListsByDirectory($directoryId);
		foreach ($directory_listings as $listing) {
			$listing2level = $listing->getListing2level();
			$listing_level_ids = array();
			foreach ($listing2level as $l2l) {
				$level = $l2l->getLevel();
				array_push($listing_level_ids, $level->getId());
				while($level->getParentId() != null){
					$level = Doctrine_Core::getTable('Level')->find($level->getParentId());
					array_push($listing_level_ids, $level->getId());
				}

			}
			if(count(array_intersect($template_level_ids, $listing_level_ids)) > 0){
				array_push($listingsForTemplate, $listing);
			}
		}
			
		return $listingsForTemplate;
			
	}

	public function executeShow(sfWebRequest $request)
	{
		$this->template_content = Doctrine_Core::getTable('TemplateContent')->find(array($request->getParameter('id')));
		$this->forward404Unless($this->template_content);
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->form = new TemplateContentForm();
	}

	public function executeCreate(sfWebRequest $request)
	{
			
		$this->forward404Unless($request->isMethod(sfRequest::POST));

		//$form = new TemplateContentForm();

		// $this->processForm($request, $form);
			
		$content_types = Doctrine_Core::getTable('ContentType')->retreiveActiveContentTypes();
			
		$template_content_arr = array();
			
		foreach ($content_types as $content_type) {


			if ($content_type->getId() != sfConfig::get('app_content_type_footer')){

				$the_content = $request->getParameter('ta_'.$content_type->getId());

				$templateContent = Doctrine_Core::getTable('TemplateContent')->getTemplateContent($request->getParameter('template_id'), $content_type->getId());

				$templateContent = $templateContent == null ? new TemplateContent() : $templateContent;

				$templateContent->setContentTypeId($content_type->getId());

				$templateContent->setTemplateId($request->getParameter('template_id'));

				if ($request->getParameter('include_api_code') != 1 && $content_type->getId() == sfConfig::get('app_content_type_body')){
					$the_content = str_replace("#%%#places_api_content#%%#", "", $the_content);
				}

				if ($request->getParameter('include_weather_api') != 1 && $content_type->getId() == sfConfig::get('app_content_type_body')){
					$the_content = str_replace("#%%#weather_api#%%#", "", $the_content);
				}

				if ($request->getParameter('include_maps_api') != 1 && $content_type->getId() == sfConfig::get('app_content_type_body')){
					$the_content = str_replace("#%%#maps_api#%%#", "", $the_content);
				}


				$templateContent->setTheContent($the_content);

				$templateContent->save();

				$template_content_arr[$content_type->getId()] = $templateContent;

			}
		}

		$template = Doctrine_Core::getTable('Template')->find(array($request->getParameter('template_id')));

		$alias_when_footer = $request->getParameter('tx_footer_alias');

		$template->setAliasWhenFooter($alias_when_footer);
		//$template->save();



		if ($request->getParameter('sl_template_footer') != ""){
			$template->setFooterId($request->getParameter('sl_template_footer'));



			//$template->save();
		}

		$template->setIncludeApiCode($request->getParameter('include_api_code'));

		$template->setIncludeMapsApi($request->getParameter('include_maps_api'));

		if ($request->getParameter('include_api_code') == 1){
			$template->setSearchStr($request->getParameter('tx_search_variables'));
			$template->setSearchTypes($request->getParameter('search_type'));
			$template->setSearchResultsCount($request->getParameter('search_results_count'));
		}
		else{
			$template->setSearchStr("");
			$template->setSearchTypes("");

		}

		$template->setIncludeWeatherApi($request->getParameter('include_weather_api'));
		if ($request->getParameter('include_weather_api') == 1){
			$template->setWeatherTarget($request->getParameter('weather_target'));
		}
		else{
			$template->setWeatherTarget("");
		}

		$template->save();
			

		$all_levels = $this->getLevels($request->getParameter('template_id'));

		$this->getUser()->setFlash('test_flash', 'Object saved');

		$action_str = "Contents saved for template ID: " . $template->getId();
		DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));

		//return $this->renderPartial('the_content', array('template' =>$template, 'content_types' => $content_types, 'all_levels' => $all_levels, 'template_content_arr' => $template_content_arr, 'deletable' => true));
		return $this->redirect('template_content/index?template_id=' . $request->getParameter('template_id'));
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->forward404Unless($template_content = Doctrine_Core::getTable('TemplateContent')->find(array($request->getParameter('id'))), sprintf('Object template_content does not exist (%s).', $request->getParameter('id')));
		$this->form = new TemplateContentForm($template_content);
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($template_content = Doctrine_Core::getTable('TemplateContent')->find(array($request->getParameter('id'))), sprintf('Object template_content does not exist (%s).', $request->getParameter('id')));
		$this->form = new TemplateContentForm($template_content);

		$this->processForm($request, $this->form);

		$this->setTemplate('edit');
	}

	public function executeDelete(sfWebRequest $request)
	{
		//$request->checkCSRFProtection();

		$template_id = $request->getParameter('template_id');

		$content_types = Doctrine_Core::getTable('ContentType')->retreiveActiveContentTypes();
			

		$template_contents = Doctrine_Core::getTable('TemplateContent')->getTemplateContentByTemplateId($template_id);

		foreach ($template_contents as $template_content) {
			$template_content->delete();
		}
			
		$action_str = "Contents deleted for template ID: " . $template_id;
		DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));

		//$this->forward404Unless($template_content = Doctrine_Core::getTable('TemplateContent')->find(array($request->getParameter('id'))), sprintf('Object template_content does not exist (%s).', $request->getParameter('id')));
		//$template_content->delete();

		$this->redirect('templates/index');
	}

	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
		if ($form->isValid())
		{
			$template_content = $form->save();

			//$this->redirect('template_content/edit?id='.$template_content->getId());
		}
	}

	protected function getLevels($template_id){
		$template2levels = Doctrine_Core::getTable('Template2Level')->getTemplatesLevelsByTemplateId($template_id);

		$all_levels = array();

		foreach ($template2levels as $template2level){
			array_push($all_levels, $template2level);
			foreach ($template2level->getUpperLevel() as $upper_level){
				array_push($all_levels, $upper_level);
			}
			foreach ($template2level->getSideLevel() as $side_level){
				array_push($all_levels, $side_level);
			}
		}

		return $all_levels;
	}

	protected function getTemplatesForFooter($template){
		$templates_for_footer = array();
		$main_levels = array();
		/*
		 $main_url_template_content = Doctrine_Core::getTable('TemplateContent')->getTemplateContent($template->getId(), sfConfig::get('app_content_type_url'));

		 $main_content = $main_url_template_content->getTheContent();

		 $template2level_ids = array();

		 foreach($template->getTemplate2Level() as $template2level){
		 array_push($template2level_ids, $template2level->getId());
		 }

		 $main_variables_name = array ();
		 $matchPattern = "/#%#(.*?)#%#/";
		 if (preg_match_all ( $matchPattern, $main_content, $matches )) {
		 $main_variables_name = $matches [1];
		 }

		 $main_levels = array();

		 foreach ($main_variables_name as $main_variable_name){
		 $level = $this->locateLevel($main_variable_name, $template, $template2level_ids);
		 array_push($main_levels, $level);
		 }
		 */
			
		foreach($template->getTemplate2Level() as $template2level){
			array_push($main_levels, $template2level->getLevel());
		}
			
		$all_level_ids = array();

		foreach ($main_levels as $main_level){
			array_push($all_level_ids, $main_level->getId());
			$children = $main_level->getLevel();
			foreach($children as $child){
				array_push($all_level_ids, $child->getId());
			}
		}

		$all_level_ids = array_unique($all_level_ids);

			
		//directory's templates
		$template2levels = $template->getTemplate2Level() ;
		$direcctoryId = count($template2levels) > 0 ? $template2levels[0]->getLevel()->getCategory()->getMasterDirectoryId() : $template->getDirectoryForHomeTemplate()->getId();
		$directory_templates = Doctrine_Core::getTable('Template')->retreiveActiveTemplatesByDirectory($direcctoryId);

		foreach ($directory_templates as $directory_template){
		 if ($directory_template->getId() != $template->getId()){
		 	$url_template_content = Doctrine_Core::getTable('TemplateContent')->getTemplateContent($directory_template->getId(), sfConfig::get('app_content_type_url'));

		 	if ($url_template_content != null){
		 		$the_content = $url_template_content->getTheContent();


		 		$variables_name = array ();
		 		$matchPattern = "/#%#(.*?)#%#/";
		 		if (preg_match_all ( $matchPattern, $the_content, $matches )) {
		 			$variables_name = $matches [1];
		 		}

		 		if (count($variables_name) == 1){
		 			array_push($templates_for_footer, $directory_template);
		 		}
		 		else{
		 			$directory_template2level_ids = array();
		 			foreach ($directory_template->getTemplate2Level() as $directory_template2level){
		 				array_push($directory_template2level_ids, $directory_template2level->getId());
		 			}
		 				
		 			$variable_found = false;
		 			$index = 0;
		 			while(!$variable_found && $index < count($variables_name) ){
		 				$level = $this->locateLevel($variables_name[$index], $directory_template, $directory_template2level_ids);
		 				if ( in_array($level->getId(), $all_level_ids) ){
		 					$variable_found = true;
		 					array_push($templates_for_footer, $directory_template);
		 				}
		 				$index ++;
		 			}
		 				
		 		}

		 	}
		 	 
		 }
		}

		return $templates_for_footer;
	}

	public function getTemplateCategories($template){
		$arr_categories = array();
		foreach ($template->getTemplate2Level() as $template2level){
			array_push($arr_categories, $template2level->getLevel()->getCategory());
		}
		return array_unique($arr_categories);
			
	}

	protected function locateLevel($main_variable_name, $template, $template2level_ids){
		//echo $main_variable_name . '<br>';
		//foreach ($main_variables_name as $main_variable_name){
		//look for the variable in template2level
		$level = null;
		$templates2level = Doctrine_Core::getTable('Template2Level')->getTemplate2LevelByName($template->getId(), $main_variable_name);
		if ($templates2level != null){
			$level = $templates2level->getLevel();
		}
		else {
			//look for the variable in upper_level
			$upper_level = Doctrine_Core::getTable ( 'UpperLevel' )->getUpperLevelByName($template2level_ids, $main_variable_name);
			if ($upper_level != null){
				$level = $upper_level->getLevel();
			}
			else{
				$level = Doctrine_Core::getTable('SideLevel')->getSideLevelByName($template2level_ids, $main_variable_name)->getLevel();
			}
		}
		return $level;
		//}
	}

}
